import { Map, View } from 'ol'
import Tile from 'ol/layer/Tile'
import WMTS from 'ol/source/WMTS'
import { get as getProjection } from 'ol/proj'
import { getWidth } from 'ol/extent'
import TileGrid from 'ol/tilegrid/WMTS'
import { getTopLeft } from 'ol/extent'

export function useOpenlayersMap(mapContainerID: string) {
  const projection = getProjection('EPSG:4326')
  const projectionExtent = projection?.getExtent()
  const size = getWidth(projectionExtent!) / 256
  const resolutions = []
  for (let z = 1; z < 19; z++) {
    resolutions[z] = size / Math.pow(2, z)
  }
  const tiandiVec = new Tile({
    source: new WMTS({
      url: 'http://t0.tianditu.gov.cn/vec_c/wmts?tk=1d109683f4d84198e37a38c442d68311',
      layer: 'vec',
      style: 'default',
      matrixSet: 'c',
      format: 'tiles',
      wrapX: true,
      tileGrid: new TileGrid({
        origin: getTopLeft(projectionExtent!),
        resolutions: resolutions,
        matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18']
      })
    })
  })
  const tiandiCva = new Tile({
    source: new WMTS({
      url: 'http://t0.tianditu.gov.cn/cva_c/wmts?tk=1d109683f4d84198e37a38c442d68311',
      layer: 'cva',
      style: 'default',
      matrixSet: 'c',
      format: 'tiles',
      wrapX: true,
      tileGrid: new TileGrid({
        origin: getTopLeft(projectionExtent!),
        resolutions: resolutions,
        matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18']
      })
    })
  })
  onMounted(() => {
    window.map = new Map({
      target: document.getElementById(mapContainerID)!,
      layers: [tiandiVec, tiandiCva],
      view: new View({
        center: [120.1, 8.85],
        zoom: 4,
        projection: 'EPSG:4326',
        multiWorld: true
      })
    })
  })
  return { tiandiVec, tiandiCva }
}
